<template>
  <div class="paper-detail-container">
    <h1>{{ paper.paperTitle || '论文详情' }}</h1>
    <el-card shadow="hover" class="form-section">
      <template #header>
        <div class="card-header">
          <span>论文基本信息</span>
          <el-tag v-if="paper.status !== undefined" :type="getStatusTagType(paper.status)" style="margin-left: 10px">
            {{ getStatusText(paper.status) }}
          </el-tag>
          <el-button
              v-if="isEditable"
              style="float: right;"
              type="primary"
              @click="handleEdit"
          >
            编辑
          </el-button>
        </div>
      </template>

      <div v-if="loading" class="loading-state">
        <i class="el-icon-loading"></i>
        正在加载论文详情...
      </div>

      <div v-else-if="!paper.id" class="empty-state">
        <img src="@/assets/images/empty-paper.png" alt="论文不存在" class="empty-image">
        <p class="empty-text">论文不存在或已被删除</p>
        <el-button type="primary" @click="backToList">返回列表</el-button>
      </div>

      <div v-else>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">论文标题:</span>
              <span class="info-value">{{ paper.paperTitle || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">期刊名称:</span>
              <span class="info-value">{{ paper.journal || '--' }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <span class="info-label">卷号:</span>
              <span class="info-value">{{ paper.volume || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="info-label">期号:</span>
              <span class="info-value">{{ paper.issue || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">页码范围:</span>
              <span class="info-value">{{ paper.pageRange || '--' }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <span class="info-label">检索级别:</span>
              <span class="info-value">{{ paper.indexLevel || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="info-label">影响因子:</span>
              <span class="info-value">{{ paper.impactFactor || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="info-label">发表日期:</span>
              <span class="info-value">{{ formatDate(paper.publishDate) }}</span>
            </div>
          </el-col>
        </el-row>

        <div class="info-item">
          <span class="info-label">论文链接/DOI:</span>
          <span class="info-value">
            <el-link v-if="paper.paperLink" :href="normalizePaperLink(paper.paperLink)" target="_blank" type="primary">
              {{ paper.paperLink }}
            </el-link>
            <span v-else>--</span>
          </span>
        </div>
      </div>
    </el-card>

    <!-- 作者信息 -->
    <el-card shadow="hover" class="form-section">
      <template #header>
        <div class="card-header">
          <span>作者信息</span>
        </div>
      </template>

      <div class="info-item">
        <span class="info-label">第一作者:</span>
        <span class="info-value">{{ paper.firstAuthor || '--' }}</span>
      </div>

      <div class="info-item">
        <span class="info-label">通讯作者:</span>
        <span class="info-value">{{ paper.correspondingAuthor || '--' }}</span>
      </div>

      <div class="info-item">
        <span class="info-label">作者名单:</span>
        <div class="author-tags">
          <el-tag
              v-for="(author, index) in parsedAuthors"
              :key="index"
              :type="getAuthorTagType(author)"
              class="author-tag"
          >
            {{ author.name }}
            <span v-if="author.affiliation" class="author-affiliation">({{ author.affiliation }})</span>
            <span v-if="author.name === paper.firstAuthor" class="first-author-badge">一作</span>
            <span v-if="author.name === paper.correspondingAuthor" class="corresponding-badge">通讯</span>
          </el-tag>
        </div>
      </div>
    </el-card>

    <!-- 审核记录 -->
    <el-card shadow="hover" class="form-section" v-if="paper.status !== 0">
      <template #header>
        <div class="card-header">
          <span>审核记录</span>
          <el-button
              v-if="paper.status === 1 || paper.status === 3"
              style="float: right;"
              type="text"
              :icon="Refresh"
              @click="fetchAuditRecords(paper.id)"
          >
            刷新
          </el-button>
        </div>
      </template>

      <el-timeline v-if="auditRecords.length > 0">
        <el-timeline-item
            v-for="(record, index) in auditRecords"
            :key="index"
            :timestamp="formatDateTime(record.auditTime)"
            placement="top"
        >
          <el-card shadow="hover">
            <div class="audit-record">
              <div class="audit-result">
                <el-tag :type="getAuditResultType(record.auditResult)" size="small">
                  {{ getAuditResultText(record.auditResult) }}
                </el-tag>
                <span class="auditor">审核人ID: {{ record.auditUserId || '系统' }}</span>
              </div>
              <div v-if="record.auditComment" class="audit-comment">
                <div class="comment-title">审核意见:</div>
                <div class="comment-content">{{ record.auditComment }}</div>
              </div>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <div v-else class="empty-audit">
        <template v-if="paper.status === 1">
          <i class="el-icon-time"></i> 论文已提交，等待审核中...
        </template>
        <template v-else>
          <i class="el-icon-info"></i> 暂无审核记录
        </template>
      </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button
          type="primary"
          @click="openPaperLink"
          :disabled="!paper.paperLink"
      >
        <i class="el-icon-link"></i> 查看论文
      </el-button>
      <el-button @click="backToList">
        <i class="el-icon-back"></i> 返回列表
      </el-button>
      <el-button
          v-if="canDelete"
          type="danger"
          @click="handleDelete"
      >
        <i class="el-icon-delete"></i> 删除论文
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import dayjs from 'dayjs'
import paperApi from '@/api/paper.js'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

const paper = ref({})
const loading = ref(false)
const auditRecords = ref([])
const auditRecordsLoading = ref(false)

// 计算属性
const userId = computed(() => authStore.user?.userId)
const isEditable = computed(() => {
  if (!authStore.isAuthenticated) return false
  if (paper.value.submitUserId !== userId.value) return false
  return paper.value.status === 0 || paper.value.status === 3 // 草稿或需修改状态可编辑
})

const canDelete = computed(() => {
  if (!authStore.isAuthenticated) return false
  if (paper.value.submitUserId !== userId.value) return false
  return paper.value.status === 0 // 只有草稿状态可删除
})

const parsedAuthors = computed(() => {
  try {
    if (!paper.value.authors) return []
    return Array.isArray(paper.value.authors) ? paper.value.authors : []
  } catch {
    return []
  }
})

// 状态相关方法
const getStatusTagType = (status) => {
  switch (status) {
    case 0: return 'info'     // 草稿
    case 1: return ''         // 已提交
    case 2: return 'success'  // 已审核
    case 3: return 'warning'  // 需修改
    case 4: return 'danger'   // 已拒绝
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 0: return '草稿'
    case 1: return '已提交'
    case 2: return '已审核'
    case 3: return '需修改'
    case 4: return '已拒绝'
    default: return '未知状态'
  }
}

// 作者标签类型
const getAuthorTagType = (author) => {
  if (author.name === paper.value.correspondingAuthor) return 'success'
  if (author.name === paper.value.firstAuthor) return 'warning'
  return ''
}

// 审核结果类型
const getAuditResultType = (result) => {
  const map = {
    'APPROVED': 'success',
    'REJECTED': 'danger',
    'PENDING': 'info',
    'PASS': 'success',
    'FAIL': 'danger'
  }
  return map[result] || 'info'
}

const getAuditResultText = (result) => {
  const map = {
    'APPROVED': '已通过',
    'REJECTED': '已拒绝',
    'PENDING': '待审核',
    'PASS': '已通过',
    'FAIL': '已拒绝'
  }
  return map[result] || result || '未知状态'
}

// 日期格式化
const formatDate = (date) => date ? dayjs(date).format('YYYY-MM-DD') : '--'
const formatDateTime = (date) => date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '--'

// 规范化论文链接
const normalizePaperLink = (link) => link?.startsWith('http') ? link : `https://${link}`

// 获取论文详情
const fetchPaperDetails = async () => {
  try {
    loading.value = true
    const id = Number(route.params.id)
    if (!id) throw new Error('无效的论文ID')

    const response = await paperApi.getPaperDetails(id)
    paper.value = response.data || {}

    if (!paper.value.id) throw new Error('论文数据不完整')
    await fetchAuditRecords(id)
  } catch (error) {
    console.error('获取论文详情失败:', error)
    ElMessage.error(error.message || '获取论文详情失败')
    setTimeout(() => backToList(), 1500)
  } finally {
    loading.value = false
  }
}

// 获取审核记录
const fetchAuditRecords = async (paperId) => {
  try {
    auditRecordsLoading.value = true
    const response = await paperApi.getPaperAuditRecords(paperId)
    auditRecords.value = response.data || []
  } catch (error) {
    console.error('获取审核记录失败:', error)
    ElMessage.error('获取审核记录失败')
  } finally {
    auditRecordsLoading.value = false
  }
}

// 操作方法
const handleEdit = () => {
  router.push({
    name: 'PaperEdit',
    params: { id: route.params.id }
  })
}

const handleDelete = () => {
  ElMessageBox.confirm('确定要删除这篇论文吗？此操作不可撤销', '警告', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'warning',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        try {
          await paperApi.deletePaper(paper.value.id)
          ElMessage.success('论文删除成功')
          backToList()
        } catch (error) {
          ElMessage.error(error.message || '删除失败')
        } finally {
          instance.confirmButtonLoading = false
          done()
        }
      } else {
        done()
      }
    }
  })
}

const openPaperLink = () => {
  if (!paper.value.paperLink) {
    ElMessage.warning('论文链接不可用')
    return
  }
  window.open(normalizePaperLink(paper.value.paperLink), '_blank')
}

const backToList = () => {
  if (window.history.length > 1) {
    router.go(-1) // 返回上一页
  } else {
    // 如果没有历史记录，则回退到默认列表页
    const isStudent = authStore.user?.roles?.includes('STUDENT')
    router.push({ name: isStudent ? 'StudentPaperManagement' : 'PaperList' })
  }
}
// 初始化
onMounted(() => {
  fetchPaperDetails()
})
</script>

<style scoped>
.paper-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.form-section {
  margin-bottom: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  color: var(--el-color-primary);
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.empty-image {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  margin-bottom: 18px;
}

.info-label {
  font-weight: bold;
  color: #666;
  min-width: 120px;
  margin-right: 10px;
}

.info-value {
  color: #333;
  flex: 1;
}

.author-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.author-tag {
  position: relative;
  padding-right: 30px;
}

.first-author-badge,
.corresponding-badge {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 10px;
  background: rgba(255,255,255,0.7);
  padding: 1px 3px;
  border-radius: 2px;
}

.first-author-badge {
  color: #e6a23c;
}

.corresponding-badge {
  color: #67c23a;
}

.author-affiliation {
  margin-left: 5px;
  font-size: 12px;
  color: #888;
}

.audit-record {
  padding: 10px;
}

.audit-result {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.auditor {
  margin-left: 10px;
  font-size: 14px;
  color: #666;
}

.audit-comment {
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
}

.comment-title {
  font-weight: bold;
  margin-bottom: 4px;
}

.comment-content {
  white-space: pre-wrap;
}

.empty-audit {
  text-align: center;
  color: #999;
  padding: 20px 0;
  font-size: 14px;
}

.empty-audit i {
  margin-right: 5px;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

@media (max-width: 768px) {
  .paper-detail-container {
    padding: 10px;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .info-label {
    margin-bottom: 4px;
    min-width: auto;
  }

  .form-actions {
    flex-direction: column;
    align-items: center;
  }
}
</style>